package cn.com.digitalnet.ad.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import cn.com.digitalnet.ad.web.servlet.CaptchaServlet;

@Controller
@RequestMapping(value = "/login")
public class LoginController {

	@RequestMapping(method = RequestMethod.GET)
	public String login(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Servlets.setNoCacheHeader(response);
		if(SecurityUtils.getSubject().isAuthenticated()){
			SecurityUtils.getSubject().logout();
		}
		return "login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model, HttpServletResponse response) {
		Servlets.setNoCacheHeader(response);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		if(SecurityUtils.getSubject().isAuthenticated()){
			SecurityUtils.getSubject().logout();
		}
		return "login";
	}

	/**
	 * 协助jquery validator,ajax检查验证码是否正确
	 * @author qidafang
	 * @param captcha
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/checkCaptcha")
	@ResponseBody
	public boolean checkCaptcha(@RequestParam("captcha") String captcha,HttpSession session){
		String captchaInSession = (String)session.getAttribute(CaptchaServlet.KEY_CAPTCHA);
		return StringUtils.equalsIgnoreCase(captcha, captchaInSession);
	}
}
